/*
 * @Author: 徐博
 * @Date: 2023-02-16 17:29:38
 * @Last Modified by: 徐博
 * @Last Modified time: 2023-03-07 17:59:40
 */

import axios, { AxiosRequestConfig, AxiosError, AxiosResponse } from 'axios';
import { message } from 'ant-design-vue';
import FeLoading from '@/components/loading/index.vue';
import { createVNode, render, VNode } from "vue";

// 挂载spin到window上
const vNode: VNode = createVNode(FeLoading) //转成vnode
render(vNode, document.body) //转成真实dom，第二个参数是挂载在哪里
window.$loading = {
    show: vNode.component?.exposed?.show,
    hide: vNode.component?.exposed?.hide,
}


axios.defaults.timeout = 1000*6;
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=UTF-8';
//  创建axios实例
const _axios = axios.create({
    // baseURL: import.meta.env.VITE_APP_API_BASE_URL
})
// axios拦截请求

_axios.interceptors.request.use(
    (config: AxiosRequestConfig) => {
        window.$loading.show()
            config.headers = {
                ...config.headers,
            }
        return config;
    },
    (error: AxiosError) => {
        return Promise.reject(error);
    }
)

interface Response<T>  {
[x: string]: string | number
    status: number | string
    data?: any
    msg: string
}

//响应拦截
_axios.interceptors.response.use((response: AxiosResponse)=> {
    console.log(response,'response')
    window.$loading.hide();
    return response
},
(error: AxiosError) => {
    window.$loading.hide()
    if(error?.response?.status === 401) {
        message.error('当前登录已过期,请重新登录');
        sessionStorage.setItem('token', '')
        setTimeout(()=> {
            //跳转登录
            window.location.href = '/login'
        }, 800);
        return
    }else if(error?.response?.status === 400) {
        message.error(error.response.data);
    }else {
        message.error('服务开小差了，请稍后再试')
    }
    return Promise.reject(error)
}
)

export type { AxiosResponse, AxiosRequestConfig, Response }
export default _axios
